# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password
  before_filter :remember_current_url_as_http_referer,
    :login_in_2_thread,
    :error_message_follows_field,
    :authorize,
    :check_introducer

  # 郁闷哇
  UserToolSetting::NumberLocation
  
  # 登录超时验证
  def authorize    
    respond_to do |format|
      format.html do         
        redirect_to new_session_url :authorized_code_login_time_out => @authorized_code_login_time_out, 
          :http_referer => request.request_uri
      end
      format.js do
        redirect_to new_session_url(:format => :js)
      end
    end if not has_logined_by_user?
  end
  
  def authorize_for_admin
    respond_to do |format|
      format.html do         
        redirect_to new_session_url
      end
      format.js do
        redirect_to new_session_url(:format => :js)
      end
    end if not has_logined_by_admin?
  end
  
  # 介绍人检测
  def check_introducer    
    cookies.signed[:introducer_id] ||= params[:introducer_id] if params[:introducer_id].present?
    Thread.current[:introducer_id] = cookies.signed[:introducer_id]
  end
    
  
  #记录当前url作为http_referer
  def remember_current_url_as_http_referer
    @http_referer = request.request_uri
  end
  
  # 用户是否登录
  def has_logined_by_user?
    current_user_id
  end
  
  def has_logined_by_admin?
    current_user.try(:admin?)
  end
  
  # 校验错误信息显示在field后面
  def error_message_follows_field
    error_message_follows_field_by_default
  end
  
  def error_message_follows_field_by_default
    ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|      
      if instance.error_message.kind_of?(Array)
        %(#{html_tag}<span class="validation_error">&nbsp;  #{instance.error_message.join(',')}</span>)
      else
        %(#{html_tag}<span class="validation_error">&nbsp;  #{instance.error_message}</span>)
      end
    end
  end
  
  # 当前用户id
  def current_user
    begin
      @current_user ||= User.find(current_user_id)
    rescue ActiveRecord::RecordNotFound
    end
  end

  # 当前用户id
  def current_user_id
    logger.debug "params[:user_id] is #{params[:user_id]}"
    logger.debug "params[:authorized_code] is #{params[:authorized_code]}"
    # 普通登录
    if session[:current_user_id].nil? and cookies.signed[:user_id].present?
      begin
        user = User.find(cookies.signed[:user_id])
        session[:current_user_id] = user.id if user.check_security_key_in_cookies(cookies.signed[:user_security_key])        
      rescue ActiveRecord::RecordNotFound
        logger.debug "user.find(#{cookies.signed[:user_id]}) failed"
      end
    # 授权码登录
  elsif params[:user_id].present? and params[:authorized_code].present?
      logger.debug '开始授权码验证'
      begin
        user = User.find(params[:user_id])
        if user.authorized_code?(params[:authorized_code])
          session[:current_user_id] = user.id 
          logger.debug "通过授权码验证"
        else
          @authorized_code_login_time_out = true
          logger.debug "授权码验证失败"
        end
      rescue ActiveRecord::RecordNotFound
        logger.debug "user.find(#{cookies.signed[:user_id]}) failed"
      end
    else
      logger.debug "验证当前用户是否可用"
      session[:current_user_id] = nil unless User.exists?(session[:current_user_id])
    end
    session[:current_user_id]
  end
  
  def send_email_and_render
    begin
      yield
      render :status => 200, :text => '发送成功，请您到的邮箱查收'
    rescue
      render :status => 500, :text => $!
    end
  end
  
  # 发送短信并render
  def send_sm_and_render
    begin
      yield
      render :status => 200, :text => '发送成功'
    #rescue Exception => error
      #logger.error "======================="
      #logger.error error
      #logger.error "======================="      
      #case error.to_s
      #when 'Fetion Error: Login failed.'
      #  render :status => 500 , :text => '密码不正确,再试试。'
      #when 'Fetion Error: No ssic found in cookie.'
      #  render :status => 500 , :text => '飞信发送组件失效,请联系管理员解决。'
      #else
      #  render :status => 500 , :text => error
      #end
    rescue Exception => error
      logger.error "======================="
      logger.error error
      logger.error "======================="      
      render :status => 500 , :text => error
    end
#  rfetion v>=0.5.7
#    rescue Fetion::PasswordMaxError => error
#      logger.error error
#      render :status => 500 , :text => '错误尝试次数过多，请用飞信客户端登录取消该限制，请稍候重试。'
#    rescue Fetion::PasswordError => error
#      logger.error error
#      render :status => 500 , :text => '密码不正确,再试试。'
#    rescue Fetion::SipcException => error
#      logger.error error
#      render :status => 500 , :text => '飞信发送组件失效,请联系管理员解决。'
#    rescue SocketError
#      logger.error error
#      render :status => 500 , :text => '飞信服务器断网,请联系管理员解决。'
#    end
  end
  
  private
  def login_in_2_thread
    Thread.current[:current_user_id] = current_user_id
    current_user.login_at_now! if has_logined_by_user? and (not current_user.login_at.to_date.today?)
    Thread.current[:remote_ip] = request.remote_ip
  end
end
